#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import shutil
import os.path

# 文件类型字典
FILE_TYPE_DICT = {'compress': 'zip|rar|7z|iso|gz|xz',
                  'document': 'pdf|txt|log|doc|docx|xml|json|xls|xlsx|et|md|html|chm|ppt|pptx',
                  'audio': 'mp3|flac|ape|wma|ogg',
                  'software': 'exe|sh|bin|py|jar|java|deb',
                  'image': 'jpg|bmp|jpeg|png|ico',
                  'video': 'mp4|avi|rm|rmvb|wmv|mov'}
DIRECTORY_CATEGORY = {'normal': '常规', 'compress': '压缩文件', 'document': '文档',
                      'audio': '音乐', 'software': '程序', 'video': '视频',
                      'directory': '文件夹', 'image': '图片'}


def files_sort_out(folder_path):
    '''整理所有文件，含文件夹'''
    if str.strip(folder_path) != '':
        # 创建需要分类的文件夹
        category_names = ('常规', '压缩文件', '文档', '音乐', '程序', '视频',
                          '文件夹', '图片')
        for dirname in category_names:
            create_dirs_if_not_exist(os.path.join(folder_path, dirname))
        print('开始处理目录：' + folder_path)
        for filename in os.listdir(folder_path):
            move_file_by_category(folder_path, filename)
        print('处理完成！')


def create_dirs_if_not_exist(dir_path):
    '''如果指定的文件不存在则创建'''
    if str.strip(dir_path) != '':
        if not os.path.isdir(dir_path):
            print('创建目录->' + dir_path)
            os.makedirs(dir_path)
    else:
        print('待创建的目录名不能为空！')


def move_file_by_category(folder_path, filename):
    file_category = ''
    '''根据分类移动文件'''
    for category, exts in FILE_TYPE_DICT.items():
        file_ext = os.path.splitext(filename)[1]
        file_path = os.path.join(folder_path, filename)
        if len(file_ext) == 0:
            if os.path.isdir(file_path):
                if not filename in DIRECTORY_CATEGORY.values():
                    file_category = 'directory'
            else:
                file_category = 'normal'
            break
        else:
            if os.path.isdir(file_path):
                file_category = 'directory'
            elif file_ext.lower()[1:] in exts:
                file_category = category
                break
    if len(file_category) != 0:
        for category, directory in DIRECTORY_CATEGORY.items():
            if file_category == category:
                move_file_or_directory(folder_path, directory, filename)
                break


def move_file_or_directory(folder_path, dest_dir, filename):
    # 获取上一级目录
    src_path = os.path.join(folder_path, filename)
    dest_path = os.path.join(folder_path, dest_dir + os.path.sep + filename)
    if os.path.isdir(src_path):
        print('移动文件夹：' + src_path + ' 至' + dest_path)
    else:
        print('移动文件：' + src_path + ' 至' + dest_path)
    shutil.move(src_path, dest_path)


download_path = '/home/paul/Downloads'
files_sort_out(download_path)
